package com.eascs.dubbo.api.admin;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.eascs.admin.api.form.O2oAfterLoanForm;
import com.eascs.admin.api.loanapply.AdminApiService;
import com.eascs.admin.o2o.BankInfoVo;
import com.eascs.admin.o2o.FinanceCheck;
import com.eascs.admin.o2o.backfee.service.O2OComBankFeeService;
import com.eascs.admin.o2o.detail.form.DetailFrom;
import com.eascs.admin.o2o.internal.service.AuditCommentService;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.entity.O2oSDEntity;
import com.eascs.admin.o2o.loan.form.LoanUserForm;
import com.eascs.admin.o2o.loan.service.O2oLoanUserService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.o2o.loan.service.O2oSdService;
import com.eascs.admin.o2o.o2ozx.serviceimpl.O2oZxServiceImpl;
import com.eascs.admin.o2o.o2ozx.trans.O2oUserZxTransFormart;
import com.eascs.admin.o2o.zx.entity.O2oLoanUserEntityZx;
import com.eascs.admin.o2o.zx.entity.O2oZxEntity;
import com.eascs.admin.o2o.zx.service.IO2oLoanUserService;
import com.eascs.admin.recordlog.servcie.O2oRecordLogService;
import com.eascs.admin.recordlog.vo.O2oRecordLogVo;
import com.eascs.afterloan.service.O2oAfterService;
import com.eascs.afterloancheck.service.LoanCheckServicce;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.archive.entity.CreditArchiveRecordEntity;
import com.eascs.archive.form.ArchivequeryForm;
import com.eascs.archive.service.ArchiveRecordService;
import com.eascs.brand.entity.O2oBrandEntity;
import com.eascs.brand.form.O2oBranPage;
import com.eascs.brand.service.O2oBrandService;
import com.eascs.brand.service.O2oPartnerService;
import com.eascs.crm.nsEditDetail.service.CustomerShopInfoService;
import com.eascs.gaczcontract.entity.CustomerBasicInfo;
import com.eascs.loan.entity.O2oBankLoanData;
import com.eascs.loan.form.O2oPaymentsForm;
import com.eascs.loan.service.O2oLoanService;
import com.eascs.loan.service.O2oPaymentsService;
import com.eascs.overdue.service.O2oOverdueService;
import com.eascs.workflow.common.entity.wf.DicData;
import com.eascs.workflow.common.service.dictionary.DicDataService;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.form.ZXPTCWForm;
/**
 * 业务dubbo服务化----提供APP业务支撑
 * @author ycz
 *
 */
@Service
public class AdminApiServiceImpl implements AdminApiService {

	private final Logger logger = LoggerFactory.getLogger(AdminApiServiceImpl.class);

	@Autowired
	O2oLoanapplyService o2oLoanapplyService;
	
	@Autowired
	O2oAfterService o2oAfterService;

	@Autowired
	AuditCommentService auditCommentService;
	
	@Autowired
	IO2oLoanUserService iO2oLoanUserService;
	
	@Autowired
	O2oZxServiceImpl o2oZxServiceImpl;
	
	@Autowired
	O2oSdService o2oSdService;

	@Autowired
	LoanCheckServicce loanCheckServicce;

	@Autowired
	O2oOverdueService o2oOverdueService;

	@Autowired
	O2oPaymentsService o2oPaymentsService;

	@Autowired
	O2oLoanUserService o2oLoanUserService;

	@Autowired
	ArchiveRecordService archiveRecordService;

	@Autowired
	O2oBrandService brandService;

	@Autowired
	O2oPartnerService partnerService;

	@Autowired
	O2oRecordLogService recordService;

	@Autowired
	O2OComBankFeeService o2oComBankFeeService;
	
	@Autowired
	CustomerShopInfoService shopInfoService;

	@Reference
	private WorkFlowService workFlowService;
	
	@Reference
	private DicDataService dicDataService;
	
	@Reference
	AdminApiService adminApiService;
	
	@Autowired
	O2oLoanService o2oLoanService;
	
	@Value("${sd.url}")
	private String sdUrl;

	/**
	 * 贷款单基本信息
	 * 
	 * @param loanapplyNo
	 * @return
	 */
	@Override
	public O2oLoanapplyEntity queryByLoanapplyNo(String loanapplyNo) {
		return o2oLoanapplyService.findById(loanapplyNo);
	}

	/**
	 * 借款人基本信息
	 * 
	 * @param loanapply
	 * @return
	 */
	@Override
	public O2oLoanUserEntity queryLoanUser(O2oLoanapplyEntity loanapply) {
		return o2oLoanapplyService.findLoanUserEntity(loanapply.getLoanapplyNo(), loanapply.getLoanId());
	}

	/**
	 * 审批额度与收费费率
	 * 
	 * @param loanapplyNo
	 * @return
	 */
	@Override
	public PageResult<Object[]> queryApprovalRate(String loanapplyNo) {
		return auditCommentService.findAuditList(loanapplyNo);
	}

	/**
	 * 财务审核SD信息
	 */
	@Override
	public O2oSDEntity querySdByLoanapplyNo(String loanapplyNo) {
		return o2oSdService.getById(loanapplyNo);
	}

	/**
	 * 贷后定期检查列表
	 */
	@Override
	public PageResult<Object[]> queryAfterLoanCheck(String billCode) {
		return loanCheckServicce.listCheckLoanEntity(billCode);
	}

	/**
	 * 代偿和逾期信息
	 */
	@Override
	public PageResult<Object[]> queryCompensationAndOverdue(String billCode) {
		return o2oOverdueService.queryOverDue(billCode);
	}

	/**
	 * 还款计划信息
	 */
	@Override
	public PageResult<Object[]> queryRepaymentPlan(String billCode) {
		O2oPaymentsForm o2oPaymentsForm = new O2oPaymentsForm();
		o2oPaymentsForm.setPageSize(Integer.MAX_VALUE);
		o2oPaymentsForm.setBillCode(billCode);
		return o2oPaymentsService.paymentsList(o2oPaymentsForm);
	}

	/**
	 * 担保人详情
	 */
	@Override
	public PageResult<Object[]> querySponsorDetail(String loanapplyNo) {
		LoanUserForm loanUserForm = new LoanUserForm();
		loanUserForm.setLoanapplyNo(loanapplyNo);
		return o2oLoanUserService.findSponsor(loanUserForm);
	}

	/**
	 * 查询征信归档流程记录表
	 * 
	 * @param archivequeryForm
	 * @return
	 */
	@Override
	public CreditArchiveRecordEntity queryCreditArchiveRecord(ArchivequeryForm archivequeryForm) {
		return archiveRecordService.getById(archivequeryForm.getId());
	}

	/**
	 * 查询征信归档附件
	 * 
	 * @param id
	 * @return
	 */
	@Override
	public PageResult<Object[]> queryCreditArchiveFilesById(String id) {
		return o2oLoanapplyService.findO2oDataListEntityById(id);
	}

	/**
	 * 查询品牌信息
	 * 
	 * @param id
	 * @return
	 */
	@Override
	public O2oBrandEntity queryBrandEntityById(String id) {
		return brandService.queryBrandEntityById(id).getModel();
	}

	/**
	 * 根据ID和附件类型查询附件信息
	 * 
	 * @param loanapplyNo
	 * @param code
	 * @return
	 */
	@Override
	public PageResult<Object[]> queryO2oDataListEntityById(String id, String code) {
		return o2oLoanapplyService.findO2oDataListEntityById(id, "'" + code + "'");
	}

	/**
	 * 查询合作方
	 * 
	 * @param branPage(brandId)
	 * @return
	 */
	@Override
	public PageResult<Object[]> queryPartnerEntityByPage(O2oBranPage branPage) {
		return partnerService.queryPartnerEntityByPage(branPage).getModel();
	}

	/**
	 * 合作方修改记录
	 * 
	 * @param o2oRecordLogVo(logType)
	 * @return
	 */
	@Override
	public PageResult<Object[]> queryPartnerLogByPage(O2oRecordLogVo o2oRecordLogVo) {
		return recordService.findPartnerLogByPage(o2oRecordLogVo);
	}

	/**
	 * SD系统交易记录汇总表
	 * 
	 * @param customerSd
	 * @param cno
	 * @return
	 */
	@Override
	public List<Object[]> getSdTradeInfo(String customerSd, String cno) {
		SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM");
		String data = "<requestxml><customerCode>" + customerSd + "</customerCode><cno>" + cno + "</cno><beginDate>" + dateFormater.format(new Date()) + "</beginDate></requestxml>";
		List<Object[]> listData = new ArrayList<>();
		try {
			org.apache.axis.client.Service service = new org.apache.axis.client.Service();
			org.apache.axis.client.Call call = (org.apache.axis.client.Call) service.createCall();
			call.setTargetEndpointAddress(sdUrl);
			call.setOperationName("getSDStoreSalesAndReceivedData");
			call.setTimeout(20000);
			String s = (String) call.invoke(new String[] { data });
			Document doc = DocumentHelper.parseText(s);
			Element root = doc.getRootElement().element("statisticsList");
			if (root != null) {
				@SuppressWarnings("unchecked")
				List<Element> list = root.elements();
				SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
				DecimalFormat decimalFormat = new DecimalFormat(",##0.00");
				for (Element e : list) {
					double salesMoney = Double.valueOf(String.valueOf(e.element("salesMoney").getData() == null ? 0l : e.element("salesMoney").getData()));
					double receivedMoney = Double.valueOf(String.valueOf(e.element("receivedMoney").getData() == null ? 0l : e.element("receivedMoney").getData()));
					double yingshou = salesMoney - receivedMoney;
					Object[] b = new Object[] { e.element("statisticDate").getData(), date.format(new Date()), decimalFormat.format(salesMoney), decimalFormat.format(receivedMoney), decimalFormat.format(yingshou) };
					listData.add(b);
				}
			} else {
				listData = null;
			}
		} catch (Exception e) {
			listData = null;
			logger.warn("error:{[]}", e.getMessage());
		}
		return listData;
	}

	/**
	 * 银行卡信息
	 * 
	 * @param loanapplyNo
	 * @return
	 */
	@Override
	public BankInfoVo getBankInfo(String loanapplyNo) {
		BankInfoVo bankInfoVo = new BankInfoVo();
		O2oLoanapplyEntity loanapply = o2oLoanapplyService.findById(loanapplyNo);
		O2oLoanUserEntity loanUser = o2oLoanapplyService.findLoanUserEntity(loanapply.getLoanapplyNo(), loanapply.getLoanId());
		bankInfoVo.setUserFullName(loanUser.getUserFullName());
		bankInfoVo.setReceiveBank(loanapply.getReceiveBank());
		bankInfoVo.setBankAccount(loanapply.getBankAccount());
		return bankInfoVo;
	}

	/**
	 * 电核反馈信息
	 * 
	 * @param zXPTCWForm
	 * @return
	 */

	@Override
	public O2oLoanapplyEntity getPhoneMessageView(String referId) {
		O2oLoanapplyEntity loanEntity = o2oLoanapplyService.findById(referId);
		return loanEntity;
	}

	/**
	 * 夫妻双方历史收退费情况
	 * 
	 * @param loanId
	 * @param loanapplyNo
	 * @return
	 */
	@Override
	public PageResult<Object[]> getHistoryRefund(String loanId, String loanapplyNo) {
		O2oLoanUserEntity materEntity = o2oLoanUserService.findSpouseId(loanId, loanapplyNo);
		PageResult<Object[]> o2opageResult = null;
		if (materEntity == null) {
			o2opageResult = o2oComBankFeeService.findDBByPage(loanId, "");
		} else {
			o2opageResult = o2oComBankFeeService.findDBByPage(loanId, materEntity.getLoanId());
		}
		return o2opageResult;
	}

	@Override
	public PageResult<Object[]> findAfterLoanByPage(O2oAfterLoanForm afterLoanForm) {
		return o2oAfterService.getO2oAfterLoanByPageNew(afterLoanForm);
	}

	/**
	 * 根据流程大类查询流程类型（待办、已办、我发起的）
	 * 
	 * @param catagory
	 * @return
	 */
	@Override
	public List<Object[]> getProcessTypeByCatagory(String catagory) {
		List<DicData> dicList = workFlowService.getProcessTypeByCatagory(catagory).getModel();
		List<Object[]> processTypes = new ArrayList<>();
		if(dicList!=null&&dicList.size()!=0){
			for(int i = 0; i < dicList.size(); i ++ ){
				processTypes.add(new Object[] { dicList.get(i).getCode(), dicList.get(i).getName() });
			}
		}else{
			processTypes = null;
		}
		return processTypes;
	}

	/**
	 * 查询流程大类（待办、已办、我发起的）
	 * 
	 * @return
	 */
	@Override
	public List<Object[]> getCatagory(String subName) {
		List<DicData> catagoryList = dicDataService.getDicDataByType("processCatagory").getModel();
		List<Object[]> catagorys = new ArrayList<>();
		if (catagoryList != null && catagoryList.size() != 0) {
			for (int i = 0; i < catagoryList.size(); i++) {
				List<Object[]> process = getProcessTypeByCatagory(catagoryList.get(i).getCode());
				if (process != null) {
					catagorys.add(new Object[] { catagoryList.get(i).getCode(), catagoryList.get(i).getName(), process, subName });
				}
			}
		} else {
			catagorys = null;
		}
		return catagorys;
	}

	/*
	 * 财务审核记录
	 */
	@Override
	public FinanceCheck getFinanceCheckInfo(ZXPTCWForm zXPTCWForm) {
		FinanceCheck financeCheck=new FinanceCheck();
		O2oLoanapplyEntity loanEntity = o2oLoanapplyService.findById(zXPTCWForm.getReferId());
		if (null != loanEntity) {
			financeCheck.setEaTime(loanEntity.getEaCooperationDate());
			financeCheck.setCustomerSalesamount(loanEntity.getCustomerSalesamount());
			financeCheck.setZxRemark(loanEntity.getZxRemark());
		}
		return financeCheck;
	}

	/**
	 * 银行放款信息
	 * 
	 * @param detailForm
	 * @return
	 */
	@Override
	public O2oBankLoanData getBankLoanDate(DetailFrom detailForm) {
		return o2oLoanService.queryBillCode(detailForm.getBillCode());
	}

	@Override
	public O2oLoanUserEntity findBySomeone(String loanapplyNo, String idNum) {
		return o2oLoanUserService.findBySomeone(loanapplyNo, idNum);
	}

	@Override
	public CustomerBasicInfo getCustomerEntityById(String id) {
		return o2oLoanapplyService.getCustomerEntityById(id);
	}

	@Override
	public int checkO2ozx(String idCard) {
		return iO2oLoanUserService.checkO2ozx(idCard);
	}

	@Override
	public String applyCredit(O2oZxEntity o2oZxEntity, O2oLoanUserEntity loanUserEntity, CustomerBasicInfo customer) {
		o2oZxEntity.setBillCode(o2oZxServiceImpl.buildCode("O2OZX"));
		O2oLoanUserEntityZx o2oLoanUserEntityZx = O2oUserZxTransFormart.customerAdminToloanUser(new O2oLoanUserEntityZx(), loanUserEntity, customer);
		return o2oZxServiceImpl.saveNewEntityById(o2oZxEntity, o2oLoanUserEntityZx);
	}

}
